<?php


namespace app\api\controller\xilujob;


use app\common\controller\xilujob\XilujobApi;
use app\common\model\xilujob\Benefit;
use app\common\model\xilujob\CompanyStatistics;
use app\common\model\xilujob\Config;
use app\common\model\xilujob\EnterpriseInfo;
use app\common\model\xilujob\CompanyProfile;
use app\common\model\xilujob\Job;
use app\common\model\xilujob\JobBenefit;
use app\common\model\xilujob\JobRefreshLog;
use app\common\model\xilujob\XilujobUser;
use think\Db;
use think\Exception;
use function fast\array_except;

/**
 * 职位管理
 */
class JobManage extends XilujobApi {
    protected $noNeedLogin = [];
    protected $noNeedRight = ['*'];
    protected $restrictedActions = ['*'];

    public $company = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->company = CompanyProfile::get(['user_id'=>$this->auth->id]);
    }

    public function index() {
        $status = $this->request->param('status');
        //$company = CompanyProfile::get(['user_id'=>$this->auth->id]);
        $jobs = Job::with([
            'benefits',
            'city'=>function($query){$query->field('id,name');},
            'district'=>function($query){$query->field('id,name');},
            'work_experience',
            'education_level',
            'job_info'=>function($query){$query->field('id,job_id,failed_reason');},
        ])->where('publisher_id', $this->company->id);
        if(!in_array($status,[Job::STATUS_DISABLED, Job::STATUS_ENABLED])) {
            $jobs->whereIn('status',[Job::STATUS_AUDITING, Job::STATUS_FAILED])
                ->order('updatetime','desc');
        }else {
            $jobs->where('status', $status)->order('id','desc');
        }
        switch ($this->request->param('type')) {
            case 1:
                $jobs->where('in_hurry', 1);
                break;
            case 2:
                $jobs->where('direct',1);
                break;
            case 3:
                $jobs->where('shop', 1);
                break;
            case 4:
                $jobs->where('red_packet','>',0);
                break;
            default:
        }
        $jobs = $jobs->select();

        $jobCount = Job::where('publisher_id', $this->company->id)->count();
        $jobLimit = EnterpriseInfo::where('company_id',$this->company->id)->value('job_num_limit');

        $this->success('',['jobs'=>$jobs,'job_count'=>$jobCount,'job_limit'=>$jobLimit]);
    }

    /**
     * 企业用户，
     */
    public function action_msg() {
        $xiluuser = XilujobUser::get(['user_id'=>$this->auth->id]);
        if($xiluuser->enterprise_model->audit_status != 1) {
            $this->error('企业审核通过后方可操作');
        }
        $hasAction = Job::getAvailableNum($xiluuser->enterprise_model->id,'job_publish');
        if($hasAction<=0){
            $this->error("你的企业职位发布次数已用完，请前往购买");
        }
        $this->success('可以发布职位');
    }

    public function add() {
        $user = $this->auth->getUser();
        //$company = CompanyProfile::get(['user_id'=>$user->id]);
        if($this->request->isPost()) {
            $xilujobuser = XilujobUser::get(['user_id'=>$user->id]);
            $params = $this->request->post('', '', 'trim');
            $params = array_merge($params, [
                'publisher_id' => $this->company->id, 'publisher_type' => $xilujobuser->enterprise_group_id, 'status' => Job::STATUS_AUDITING
            ]);
            $params = array_except($params, ['in_hurry']);//不允许前端修改
            $params['user_id'] = $user->id;
            Db::startTrans();
            try {
                $job = Job::addJob($params);
            }catch (Exception $exception){
                Db::rollback();
                $this->error($exception->getMessage());
            }
            
            $job->relationQuery([
                'benefits', 'city' => function ($query) {
                    $query->field('id,name');
                }, 'district' => function ($query) {
                    $query->field('id,name');
                },
                'work_experience', 'education_level',
                'job_info' => function ($query) {
                    $query->field('id,job_id,failed_reason');
                },
            ]);
            Db::commit();
            $this->success('', ['job' => $job]);
        }
        // 获得添加时的初始数据
        $enterprise = EnterpriseInfo::get(['company_id'=>$this->company->id]);
        $job = ['type'=>1,'contact_person'=>$enterprise->contact_person,'contact_phone'=>$enterprise->contact_phone,'contact_email'=>$enterprise->contact_email];
        $this->success('', ['job'=>$job]);
    }

    public function edit($id) {
        $job = Job::get($id);
        if (!$job || $job->publisher_id != $this->company->id) {
            $this->error(__('no record'));
        }
        if($this->request->isPost()) {
            $params = $this->request->post('', '', 'trim');
            if($job->status==Job::STATUS_ENABLED) {
                $this->error('招聘中的职位无法编辑');
            }
//            if($job->status==Job::STATUS_AUDITING) {
//                $this->error('审核中的职位无法编辑');
//            }
            $params = array_except($params,['in_hurry']);//不允许前端修改
            try {
                $ret = Job::editJob($job, $params);
            }catch (Exception $e){
                $this->error($e->getMessage());
            }
            $job = $ret;
            $job->relationQuery([
                'benefits', 'city'=>function($query){$query->field('id,name');}, 'district'=>function($query){$query->field('id,name');},
                'work_experience', 'education_level', 'job_info'=>function($query){$query->field('id,failed_reason');},
            ]);
            $this->success('', ['job' => $job]);

        }
        $job = Job::with(['job_info','benefits','locations'=>['province','city','district']])->find($job->id);
        foreach($job->locations as $location) {
            $location->visible(['id','province_id','city_id','district_id','province','city','district','address','address_name','house_number','company_address_id','lat','lng']);
        }
        $job->benefit_ids = JobBenefit::where('job_id', $job->id)->column('benefit_id');
        $this->success('',['job'=>$job]);
    }

    public function del($id) {
        $job = Job::get($id);
        if (!$job || $job->publisher_id != $this->company->id) {
            $this->error(__('no record'));
        }
        try {
            $ret = Job::delJob($job);
        }catch (Exception $e){
            $this->error($e->getMessage());
        }
        $this->success('', ['job'=>$job]);
    }

    public function batch_del($ids) {
        $ids = $ids ? explode(',',$ids) : [];
        $jobs = Job::where('publisher_id', $this->company->id)->whereIn('id',$ids)->select();
        Db::startTrans();
        foreach($jobs as $job) {
            $ret = Job::delJob($job);
            if(!$ret->success) {
                $this->error($ret->msg);

            }
        }
        Db::commit();
        $this->success('');
    }

    public function switch_on($id) {
        $job = Job::get($id);
        if (!$job || $job->publisher_id != $this->company->id) {
            $this->error(__('no record'));
        }
        try {
            $ret = Job::switchOnJob($job);
        }catch (Exception $e){
            $this->error($e->getMessage());
        }
        $this->success('', $ret);

    }

    public function switch_off($id) {
        $job = Job::get($id);
        if (!$job || $job->publisher_id != $this->company->id) {
            $this->error(__('no record'));
        }
        try {
            $ret = Job::switchOffJob($job);
        }catch (Exception $e){
            $this->error($e->getMessage());
        }
        $this->success('',$ret);
    }

    public function duplicate_job($id) {
        $job = Job::get($id);
        if (!$job || $job->publisher_id != $this->auth->id) {
            $this->error(__('no record'));
        }
        $jobInfo = $job->job_info->toArray();
        $locations = collection($job->locations)->toArray();
        $benefitIds = JobBenefit::where('job_id',$id)->column('benefit_id');
        $job = array_merge($job->toArray(), $jobInfo, ['status'=>Job::STATUS_AUDITING]);
        $job['benefit_ids'] = $benefitIds;
        $ret = Job::addJob($job);
        if($ret->success) {
            $this->success('',['job'=>$ret->data]);
        }
        $this->error($ret->msg);
    }

    public function refresh_job($id) {
        $job = Job::get($id);
        if (!$job || $job->publisher_id != $this->company->id) {
            $this->error(__('no record'));
        }
        $enterpriseinfo = EnterpriseInfo::field('id,job_refresh_num')->where('company_id', $this->company->id)->find();
        $job_refresh_num = Config::getdatas("job_refresh_num") ?? 0;
        if($job_refresh_num > 0) {
            // 有免费次数
            $todayNum = JobRefreshLog::where('company_id', $job->publisher_id)
                ->count();
            $freeNum = $job_refresh_num > $todayNum ? $job_refresh_num - $todayNum : 0;
        }else {
            $freeNum = 0;
        }
        if($freeNum <= 0 && $enterpriseinfo->job_refresh_num <= 0) {
            $this->error("您购买的职位刷新数已用尽，请前往购买");
        }
        //更新企业刷新数
        Db::startTrans();
        try {
            CompanyStatistics::where('company_id', $job->publisher_id)->update(['job_refresh_count'=>Db::raw('job_refresh_count+1')]);
            $job->save(['refreshtime'=>time(), 'refresh_date'=>date('Y-m-d')]);
            //减少次数
            if($freeNum <= 0) {
                $enterpriseinfo->save(['job_refresh_num'=>Db::raw('job_refresh_num-1')]);
            }
        }catch (Exception $e){
            Db::rollback();
            $this->error($e->getMessage());
        }
        Db::commit();
        $this->success();
    }

    public function get_benefit() {
        $name = $this->request->post('name');
        if(!$name) {
            $this->error();
        }
        $benefit = Benefit::where('name', $name)->find();
        if(!$benefit) {
            $benefit = new Benefit();
            $ret = $benefit->save(['name'=>$name, 'company_id'=>$this->auth->id]);
            if($ret===false) {
                $this->error($benefit->getError());
            }
        }
        $this->success('', ['benefit'=>$benefit]);
    }


}